package com.powernode.money.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.powernode.money.constant.Constants;
import com.powernode.money.model.User;
import com.powernode.money.service.FinanceAccountService;
import com.powernode.money.service.UserService;
import com.powernode.money.vo.ApiResult;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

@Controller
public class UserController {

    @Reference(interfaceClass = UserService.class, version = "1.0.0")
    private UserService userService;
    @Reference(interfaceClass = FinanceAccountService.class,version = "1.0.0")
    private FinanceAccountService financeAccountService;

    @GetMapping("/loan/page/login")
    public String login() {
        return "login";
    }

    @GetMapping("/loan/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        Cookie cookieName = new Cookie("userName",null);
        Cookie cookieMoney = new Cookie("userMoney",null);
        cookieName.setMaxAge(0);
        cookieMoney.setMaxAge(0);
        return "redirect:/index";
    }

    @GetMapping("/jcaptcha/captcha")
    public void captcha(HttpServletResponse response, HttpSession session) {
        String code= RandomStringUtils.randomAlphabetic(4);
        session.setAttribute("captcha",code);
        response.setContentType("image/jpeg");
        BufferedImage image=new BufferedImage(120,60,BufferedImage.TYPE_INT_RGB);
        Graphics graphics=image.createGraphics();
        graphics.setColor(Color.BLUE);
        graphics.fillRect(1,1,120,60);
        graphics.setColor(Color.RED);
        Font font=new Font("Arial",Font.ITALIC,32);
        graphics.setFont(font);
        graphics.drawString(code,15,45);
        try {
            ImageIO.write(image,"jpg",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    @RequestMapping("/loan/page/loan/do-login")
    @ResponseBody
    public User doLogin(String phone, String loginPassword, HttpSession session) {
        User user = userService.queryByPhoneLoginPassword(phone, loginPassword);
        if (user != null) {
            user.setLastLoginTime(new Date());
            userService.executeUpdateByPrimaryKeySelective(user);
            session.setAttribute(Constants.SESSION_USER, user);
            session.setAttribute("money", financeAccountService.queryByUid(user.getId()));
            return user;
        } else {
            return null;
        }
    }

    @RequestMapping("/loan/page/regPhone")
    @ResponseBody
    public boolean regPhone(String phone) {
        System.out.println("----:" + phone);
        User user = userService.queryByPhone(phone);
        if (user != null) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping("/loan/page/sendSmsCode")
    @ResponseBody
    public boolean sendSmsCode(String phone) {
        if (userService.sendSmscode(phone)) {
            return true;
        } else {
            return false;
        }
    }


    @GetMapping("/loan/page/register")
    public String register() {
        return "register";
    }

    @GetMapping("/loan/page/realName")
    public String realName() {
        return "realName";
    }

    @RequestMapping("/loan/page/doRegister")
    @ResponseBody
    public boolean doRegister(String phone, String code, String loginPassword,HttpSession session) {
        if (userService.verifySmsCode(phone, code)) {
            User user = userService.register(phone, loginPassword);
            if (user != null) {
                doLogin(phone,loginPassword,session);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    @RequestMapping("/loan/page/doRealName")
    @ResponseBody
    public ApiResult doRealName(String name, String idCard,String phone,HttpSession session) {
        System.out.println(name+":"+idCard+"+"+phone);
        User user =userService.queryByPhone(phone);
        ApiResult result = userService.verifyRealName(name, idCard);
        if(result.getCode()!=200){
            return result;
        }

        User loginUser = (User)session.getAttribute(Constants.SESSION_USER);
        if(loginUser==null){
            return ApiResult.error("请先登录，再进行认证");
        }
        if (user!=null){
            System.out.println(user.getId());
            user.setIdCard(idCard);
            user.setName(name);
            int count=userService.executeUpdateByPrimaryKeySelective(user);
            if (count<0){
                return ApiResult.error("实名失败");
            }
        }
        return ApiResult.success("认证成功");
    }

    @RequestMapping("/loan/page/doCaptcha")
    @ResponseBody
    public boolean doCaptcha(String captcha,HttpSession session) {
        String code= (String) session.getAttribute("captcha");
        if (code.equals(captcha)){
            return true;
        }
        return false;
    }

}
